﻿using Grow.Module.Module;
using Grow.Module.Service;
using Grow.Scheduler.CreateScheduler;
using Grow.Scheduler.Hangfire.Memory.CreateScheduler;
using Hangfire;
using Microsoft.Extensions.DependencyInjection;

namespace Grow.Scheduler.Hangfire.Memory
{
    public abstract class SchedulerMemoryModuleBase : SchedulerModuleBase
    {
        public override void AddDependModule(IDependModuleBuilder dependModuleBuilder)
        {
        }
        public override void AddService(IServiceContainer serviceContainer)
        {
            var createSchedulerBuilder = new CreateSchedulerBuilder(serviceContainer);
            CreateScheduler(createSchedulerBuilder);
            serviceContainer.BuilderManager.SetBuilder<ICreateSchedulerBuilder>(createSchedulerBuilder);

            serviceContainer.ServiceCollection.AddSingleton<GrowJobActivator>();
            serviceContainer.ServiceCollection.AddTransient<IScheduler, Scheduler>();
        }
        public override void UseService(IServiceContext serviceContext)
        {

            var growJobActivator = serviceContext.GetRequiredService<GrowJobActivator>();
            var schedulerOptions = serviceContext.GetOptions<SchedulerOptions>();

            GlobalConfiguration.Configuration
                       .UseActivator(growJobActivator)
                       .UseInMemoryStorage();

            _ = new BackgroundJobServer(new BackgroundJobServerOptions
            {
                SchedulePollingInterval = TimeSpan.FromSeconds(schedulerOptions.UpdateSeconds),
                WorkerCount = Environment.ProcessorCount * schedulerOptions.WorkerCount
            });
        }
    }
}
